package com.fangs.kotlin_banner

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Build
import android.os.Bundle
import android.webkit.WebView
import com.ivans.videocache.HttpProxyCacheServer

class Apps : Application(), ActivityLifecycleCallbacks {

    private var httpProxyCacheServer: HttpProxyCacheServer? = null

    override fun onCreate() {
        super.onCreate()
        instance = this
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { //Android 9.0 WebView多进程问题
            val processName = getProcessName()
            if (packageName != processName) {
                WebView.setDataDirectorySuffix(processName)
            }
        }
        registerActivityLifecycleCallbacks(this)
    }

    private fun newProxy(): HttpProxyCacheServer {
        return HttpProxyCacheServer.Builder(this)
            .maxCacheSize((1024 * 1024 * 1024).toLong()) // 1 Gb for cache
            .fileNameGenerator(MyFileNameGenerator())
            .build()
    }

    override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}
    override fun onActivityStarted(activity: Activity) {}
    override fun onActivityResumed(activity: Activity) {}
    override fun onActivityPaused(activity: Activity) {}
    override fun onActivityStopped(activity: Activity) {}
    override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
    override fun onActivityDestroyed(activity: Activity) {}

    companion object {
        var instance: Apps? = null
            private set

        fun preCacherScreenData(cacheUrl: String?) {
            PreCacher.InstanceHolder.mInstance.getInstance()?.startCache(cacheUrl!!, 0)
        }

        val proxy: HttpProxyCacheServer?
            get() {
                val app = instance
                if (app!!.httpProxyCacheServer == null) {
                    app.httpProxyCacheServer = app.newProxy()
                }
                return app.httpProxyCacheServer
            }
    }
}